﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Base;

namespace HRM
{
    public partial class FormDepartment : FormBaseData
    {
        private Ctrl_General mCtrlGeneral;
        private DataSet mdsDept;
        private SqlDataAdapter mdaDeptUpdate;
        private string msIDDept = string.Empty;

        public FormDepartment()
        {
            InitializeComponent();
        }

        protected override void BasicForm_Load(object sender, EventArgs e)
        {
            base.BasicForm_Load(sender, e);
        }

        protected override void BaseForm_Activated(object sender, System.EventArgs e)
        {
            base.BaseForm_Activated(sender, e);
        }

        protected override void BaseForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            base.BaseForm_KeyDown(sender, e);
        }

        protected override void BasicForm_Closing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            base.BasicForm_Closing(sender, e);
        }

        protected override void LoadMasterData()
        {
            try
            {
                btnCancel = btncancel;
                btnOk = btnok;
                lblStatus = lblstatus;
                LoadData();
                trvDept.ExpandAll();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load Department Form'. Error: '" + ex.Message + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        private void LoadData()
        {
            try
            {
                ClearDataBinding(this);
                if (trvDept.GetNodeCount(true) > 0) trvDept.Nodes.Clear();
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string ls_SQL = "Select ID_Dept, Dept_Name, ID_Parent, CreatedUser, UpdatedUser, CreatedDate, UpdatedDate "
                    + "From HRM_Department ";

                mdsDept = mCtrlGeneral.GetSelect(ls_SQL, "HRM_Department");
                mCtrlGeneral.GetAllData(out mdaDeptUpdate, "HRM_Department", "");

                if (mdsDept == null) return;

                PopulateTreeView(trvDept.Nodes, "00", mdsDept.Tables[0]);

                txtIDDept.DataBindings.Add(new Binding("Text", mdsDept.Tables[0], "ID_Dept"));
                txtDeptName.DataBindings.Add(new Binding("Text", mdsDept.Tables[0], "Dept_Name"));

                mRowManager = (CurrencyManager)txtIDDept.BindingContext[mdsDept.Tables[0]];
                // How to refresh the status of the row position?Ordinal_Number
                mRowManager.PositionChanged += new EventHandler(RowMaster_Changed);
                SetData2List(mdsDept);
                SetReadOnly(this, false);
                base.LoadMasterData();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Department Form'. Error: '" + ex.Message + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Ctrl_LOG.Print("TDepartment form", "LoadData() method", "Error: " + ex.Message);
                Cursor = Cursors.Default;
            }
        }

        #region SetReadOnly
        //Set ReadOnly or Not for : TextBox, RadioButton, CheckBox, DateTimePicker
        private void SetReadOnly(Control aCtrl, bool abReadOnly)
        {
            foreach (Control lCtrl in aCtrl.Controls)
            {
                //MessageBox.Show(lCtrl.GetType().ToString(), lCtrl.Name);
                switch (lCtrl.GetType().ToString())
                {
                    case "System.Windows.Forms.GroupBox":
                        GroupBox lctr_groupBox = (GroupBox)lCtrl;
                        SetReadOnly(lctr_groupBox, abReadOnly);
                        break;

                    case "System.Windows.Forms.TabControl":
                        TabControl lctr_tabControl = (TabControl)lCtrl;
                        SetReadOnly(lctr_tabControl, abReadOnly);
                        break;

                    case "System.Windows.Forms.TabPage":
                        TabPage lctr_tabPage = (TabPage)lCtrl;
                        SetReadOnly(lctr_tabPage, abReadOnly);
                        break;

                    case "System.Windows.Forms.Panel":
                        Panel lctr_panel = (Panel)lCtrl;
                        SetReadOnly(lctr_panel, abReadOnly);
                        break;

                    case "System.Windows.Forms.TextBox":
                        ((TextBox)lCtrl).ReadOnly = !abReadOnly;
                        break;

                    case "System.Windows.Forms.RadioButton":
                        ((RadioButton)lCtrl).AutoCheck = abReadOnly;
                        break;

                    case "System.Windows.Forms.CheckBox":
                        ((CheckBox)lCtrl).AutoCheck = abReadOnly;
                        break;
                    case "System.Windows.Forms.DateTimePicker":
                        ((DateTimePicker)lCtrl).Enabled = abReadOnly;
                        break;

                    case "System.Windows.Forms.ComboBox":
                        ((ComboBox)lCtrl).Enabled = abReadOnly;
                        break;

                    case "System.Windows.Forms.NumericUpDown":
                        ((NumericUpDown)lCtrl).Enabled = abReadOnly;
                        break;
                }
            }
        }
        #endregion

        protected void PopulateTreeView(TreeNodeCollection parentNode, string parentID, DataTable folders)
        {
            foreach (DataRow folder in folders.Rows)
            {
                if (Convert.ToString(folder["ID_Parent"]) == parentID)
                {
                    String key = folder["ID_Dept"].ToString();
                    String text = folder["Dept_Name"].ToString();
                    TreeNodeCollection newParentNode = parentNode.Add(key, text).Nodes;
                    PopulateTreeView(newParentNode, Convert.ToString(folder["ID_Dept"]), folders);
                }
            }
        }

        public override void save()
        {
            try
            {
                if (mdsDept == null) return;
                mRowManager.EndCurrentEdit();
                if (!mdsDept.HasChanges())
                {
                    base.save();
                    return;
                }
                DataSet ldsHasChanged = mdsDept.GetChanges();
                foreach (DataRow dr in ldsHasChanged.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Added)
                    {
                        dr["ID_Parent"] = msIDDept;
                        dr["CreatedDate"] = DateTime.Now;
                        dr["CreatedUser"] = mMainForm.ms_UserID;
                    }
                    else if (dr.RowState == DataRowState.Modified)
                    {
                        dr["UpdatedDate"] = DateTime.Now;
                        dr["UpdatedUser"] = mMainForm.ms_UserID;
                    }

                    if (dr["ID_Dept"].ToString().Equals(""))
                        dr["ID_Dept"] = DBNull.Value;
                }
                string ls_ColName = "", ls_TableName = "";
                string ls_Error = mCtrlGeneral.Update(mdaDeptUpdate, ldsHasChanged, "HRM_Department", out ls_ColName, out ls_TableName);
                if (ls_Error == "")
                {
                    mdsDept.AcceptChanges();
                    int li_pos = 0;
                    if (GetCurrentAction() == MODES.MODIFY) li_pos = mRowManager.Position;
                    LoadData();
                    if (li_pos > 0) mRowManager.Position = li_pos;
                    base.save();
                    msIDDept = string.Empty;
                }
                else
                {
                    MessageBox.Show("Cannot save'. Error: '" + ls_Error + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("DB Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public override void cancel()
        {
            if (mdsDept == null) return;
            mRowManager.EndCurrentEdit();
            mdsDept.RejectChanges();
            base.cancel();
            trvDept.LabelEdit = false;
        }

        public override void add()
        {
            msIDDept = txtIDDept.Text.Trim();
            base.add();
            mRowManager.EndCurrentEdit();
            mRowManager.AddNew();
            SetReadOnly(this, true);
            mRowManager.Position = mRowManager.Count - 1;
        }

        public override void modify()
        {
            base.modify();
            SetReadOnly(this, true);
            txtIDDept.ReadOnly = true;
        }

        public override void delete()
        {
            base.delete();
            //if (!mb_AcceptDelete) return;
            //DataSet ldsDelete = (DataSet)mdbg_dataGrid.DataSource;
            //DataRow ldrDelete = ldsDelete.Tables[0].Rows[mRowManager.Position];
            //ldrDelete.Delete();
            //string lsColName = "", lsTableName = "";
            //string lsReturnMessage = mCtrlGeneral.Update(mdaDeptUpdate, ldsDelete, "HRM_Department", out lsColName, out lsTableName);
            //if (lsReturnMessage != "")
            //{
            //    MessageBox.Show("Cannot delete'. Error: '" + lsReturnMessage + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            //    ldsDelete.RejectChanges();
            //    ldsDelete.AcceptChanges();
            //}
            // base.Post_delete();
        }

        private void btnok_Click(object sender, System.EventArgs e)
        {
            save();
        }

        private void btncancel_Click(object sender, System.EventArgs e)
        {
            cancel();
        }

        private void trvDept_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                mnuAdd.Enabled = mFormRight.mb_add;
                mnuModify.Enabled = mFormRight.mb_modify;
                mnuDelete.Enabled = mFormRight.mb_delete;
            }
        }

        private void mnuAdd_Click(object sender, EventArgs e)
        {
            // Add Item here

        }

        private void mnuModify_Click(object sender, EventArgs e)
        {
            // 
            
        }

        private void mnuDelete_Click(object sender, EventArgs e)
        {
            // 

        }

    }
}
